import React, { useEffect, useRef, useState } from 'react'
import { getRightsList, getGoodById, updateGood, delGood } from '@/service/goods'
import { Card, Space, Input, Button, Tag, Tooltip } from 'antd'
import { useTranslation } from 'react-i18next'
import TableIndex from '@/components/table'
import type { ColumnsType } from 'antd/es/table'
import Dialog from '@/components/modal'
import FormIndex from '@/components/form'
import Pop from '@/components/pop'
import { formmatDateTime } from '@/utils/util'
import { useNavigate } from 'react-router-dom'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'

interface DataType {
  goods_id: number
  goods_name: string
  goods_price: number
  goods_weight: number
  goods_number: number
  goods_state: number
  add_time: number
  upd_time: number
}

export default function Goods() {
  const { t } = useTranslation()
  const navigate = useNavigate()
  const [condition, setCondition] = useState('')
  const [goodsList, setGoodsList] = useState([])
  const [pageObj, setPageObj] = useState({
    pageNum: 1,
    pageSize: 10
  })
  const [total, setTotal] = useState(0)
  const columns: ColumnsType<DataType> = [
    {
      title: t('users.table.index'),
      align: 'center',
      width: 70,
      render: (text, record, index) => index + 1
    },
    {
      title: t('goods.table.goods_name'),
      dataIndex: 'goods_name',
      align: 'center',
      ellipsis: true
    },
    {
      title: t('goods.table.goods_price'),
      dataIndex: 'goods_price',
      align: 'center',
      width: 100
    },
    {
      title: t('goods.table.goods_weight'),
      dataIndex: 'goods_weight',
      align: 'center',
      width: 100
    },
    {
      title: t('goods.table.goods_number'),
      dataIndex: 'goods_number',
      align: 'center',
      width: 100
    },
    {
      title: t('goods.table.goods_state'),
      dataIndex: 'goods_state',
      align: 'center',
      render: state => (
        <>
          {state === 0 && <Tag color="purple">{t('goods.goods_status.un_audit')}</Tag>}
          {state === 1 && <Tag color="green">{t('goods.goods_status.auditing')}</Tag>}
          {state === 2 && <Tag color="cyan">{t('goods.goods_status.audited')}</Tag>}
        </>
      ),
      width: 100
    },
    {
      title: t('goods.table.add_time'),
      dataIndex: 'add_time',
      align: 'center',
      width: 180,
      render: record => <span>{formmatDateTime(record)}</span>
    },
    {
      title: t('goods.table.upd_time'),
      dataIndex: 'upd_time',
      align: 'center',
      width: 180,
      render: record => <span>{formmatDateTime(record)}</span>
    },
    {
      title: t('users.table.action.title'),
      key: 'action',
      align: 'center',
      render: record => (
        <Space size="middle">
          <Tooltip title={t('users.table.action.edit')}>
            <Button
              type="primary"
              shape="circle"
              size="middle"
              icon={<EditOutlined />}
              onClick={() => editRow(record)}
            ></Button>
          </Tooltip>
          <Pop onConfirm={() => delRow(record)}>
            <Tooltip title={t('users.table.action.del')}>
              <Button danger type="primary" shape="circle" size="middle" icon={<DeleteOutlined />}></Button>
            </Tooltip>
          </Pop>
        </Space>
      ),
      width: 200
    }
  ]
  const [showDialog, setShowDialog] = useState<boolean>(false)
  const formRef = useRef<any>()
  const [rowData, setRowData] = useState<any>([])
  const [editFormValue, setEditFormValue] = useState<any>({
    goods_name: '',
    goods_price: '',
    goods_number: '',
    goods_weight: '',
    goods_state: null
  })
  const formConfig = [
    {
      key: 'goods_name',
      label: '商品名称',
      component: 'Input',
      rules: [{ required: true, message: '请输入商品名称' }]
    },
    {
      key: 'goods_price',
      label: '商品价格',
      component: 'Input',
      rules: [{ required: true, message: '请输入商品价格' }]
    },
    {
      key: 'goods_number',
      label: '商品数量',
      component: 'Input',
      rules: [{ required: true, message: '请输入商品数量' }]
    },
    {
      key: 'goods_weight',
      label: '商品重量',
      component: 'Input',
      rules: [{ required: false, message: '请输入商品重量' }]
    },
    {
      key: 'goods_state',
      label: '商品状态',
      component: 'Radio',
      rules: [{ required: true, message: '请选择商品状态' }],
      list: [
        { label: '未审核', value: 0 },
        { label: '审核中', value: 1 },
        { label: '已审核', value: 2 }
      ]
    }
  ]
  useEffect(() => {
    handleSearch()
  }, [condition, pageObj])
  const changeCondition = (e: any) => {
    setCondition((e.target as any).value)
  }
  const handleSearch = async () => {
    await getRightsList({
      condition,
      pageNum: pageObj.pageNum,
      pageSize: pageObj.pageSize
    }).then((res: any) => {
      const { goods, total } = res.data
      setGoodsList(goods)
      setTotal(total)
    })
  }
  const handlePageChange = (pageNum: number, pageSize: number) => {
    setPageObj({
      pageNum,
      pageSize
    })
  }
  const goGoodsAdd = () => {
    navigate('/goods_add')
  }
  const editRow = async (row: DataType) => {
    // await getGoodById({ id: row.goods_id }).then((res: any) => {
    //   setEditFormValue(res.data)
    //   const rowObj = Object.assign({}, res.data)
    //   setRowData([rowObj])
    // })
    // setShowDialog(true)
    navigate(`/goods_edit?id=${row.goods_id}`)
  }
  const delRow = async (row: DataType) => {
    await delGood({
      id: row.goods_id
    }).then(() => {
      handleSearch()
    })
  }
  const handleEditModalOk = () => {
    formRef.current?.submit()
  }
  const handleEditModalCancel = () => {
    formRef.current?.resetFields()
    setShowDialog(false)
  }
  const onFinish = async (values: any) => {
    await updateGood({
      ...rowData[0],
      id: rowData[0].goods_id,
      ...values,
      goods_price: Number(values.goods_price),
      goods_weight: Number(values.goods_weight) || null,
      goods_number: parseInt(values.goods_number)
    }).then(() => {
      handleEditModalCancel()
      handleSearch()
    })
  }
  return (
    <Card>
      <Space>
        <Input.Search
          allowClear
          style={{ width: '350px' }}
          value={condition}
          placeholder={t('users.keywords')}
          onChange={changeCondition}
          onSearch={handleSearch}
          enterButton
        />
        <Button type="primary" onClick={goGoodsAdd}>
          {t('goods.add')}
        </Button>
      </Space>
      <TableIndex
        rowKey="goods_id"
        columns={columns}
        dataSource={goodsList}
        total={total}
        pageObj={pageObj}
        handlePageChange={handlePageChange}
      />
      <Dialog
        width={500}
        title={t('goods.edit')}
        open={showDialog}
        onOk={handleEditModalOk}
        onCancel={handleEditModalCancel}
      >
        <FormIndex
          formRef={formRef}
          value={editFormValue}
          config={formConfig}
          setValue={setEditFormValue}
          onFinish={onFinish}
        ></FormIndex>
      </Dialog>
    </Card>
  )
}
